package com.sky.controller.admin;


import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
public class CommonController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);
    @Autowired
    private AliOssUtil aliOssUtil;

    /*
    * 文件上传
    * @param file
    *
    * */
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){
        log.info("文件上传：{}",file);
        try {
            // 获取原始文件名
            String originalFilename = file.getOriginalFilename();
            // 获取文件后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 构造新文件名称
            String objectName = UUID.randomUUID().toString() + extension;
            log.info("文件上传路径：{}",objectName);
            
            // 上传文件到阿里云OSS，传递正确的文件名
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            
            // 返回上传成功消息和文件访问路径
            return Result.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败：{}",e);
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
    }
}
